# Generated by Django 1.11.4 on 2017-09-04 12:01
from __future__ import unicode_literals

from django.contrib.auth import get_user_model
from django.db import migrations
from rolepermissions.checkers import has_role
from rolepermissions.permissions import revoke_permission
from rolepermissions.roles import assign_role, clear_roles


def reset_power_roles(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    User = get_user_model()
    for user in User.objects.all():
        if has_role(user, "power_user"):
            clear_roles(user)
            assign_role(user, "power_user")
        if has_role(user, "state_manager"):
            clear_roles(user)
            assign_role(user, "state_manager")


def revoke_season_see_all_from_power_roles(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    User = get_user_model()
    for user in User.objects.all():
        if has_role(user, "power_user") or has_role(user, "state_manager"):
            revoke_permission(user, "challenge_season_see_state_planning")
            user.save()


class Migration(migrations.Migration):
    dependencies = [
        ("user", "0043_allow_poweruser_to_set_roles"),
    ]

    operations = [
        migrations.RunPython(reset_power_roles, revoke_season_see_all_from_power_roles),
    ]
